/* eslint-disable react/jsx-boolean-value */
/* eslint-disable react/jsx-no-bind */
/**
 * common report 页面
 * @file 报表信息-list
 * @author liushuang(liushuang04@baijia.com)
 * @date 2019-11-06
 */
import React, {Component} from 'react';
import {QuestionCircleOutlined} from '@ant-design/icons';
import {Button, Card, Tooltip, message, Spin, Select} from 'antd';
import PropTypes from 'prop-types';
import {withRouter} from 'react-router-dom';
import {produce} from 'immer';
import moment from 'moment-timezone';

import DataDetail from '~/component/DataDetail';
import {fetchReports, downloadReports, getReportInfo} from '~/service/reports';
import SearchForm from '~/component/SearchForm';
// 时间段枚举
import getRange, {isTimeRange, INPUT_TYPE_ENUM} from '~/component/SearchForm/dateRanges';
import {buildTipText as buildTip, getDateFormat, FIELD_TIME_FORMAT} from '~/component/SearchForm/helps';

import LineChart from './lineChart';
import './index.styl';

const TOTAL = '总计';

class ReportIndex extends Component {
    static propTypes = {
        match: PropTypes.shape({
            params: PropTypes.object,
        }).isRequired,
    };

    constructor(props) {
        super(props);
        this.state = {
            name: '',
            description: '',
            // 查询接口请求参数列表
            permissions: [],
            downloadPermissions: [],
            // 指标
            reportMeasure: [],
            isloading: false,
            tableColumns: [],
            // 不带总计的数据
            dataSource: [],
            // 带总计
            summarySource: [],
            pager: {
                pageNum: 1,
                pageSize: 10,
                count: 0
            },
            // 1线图 2表格
            mapType: '1,2',
            downLoading: false,
            // 时间的类型，替代period, 分，小时，日周月， 默认 日
            period: INPUT_TYPE_ENUM.DAY,
            dateDim: 'dimension1',
            // 报表echart提示文字
            tipText: '',
            // 是否聚合，默认0不显示总计 1显示
            issummary: 0,
        };
    }

    componentDidMount() {
        this.reportDetail();
    }

    componentWillUnmount() {
        // 卸载异步操作设置状态
        this.setState = (state, callback) => false;
    }

    onPageChange = (page, size) => {
        const {pager} = this.state;
        pager.pageNum = page;
        pager.pageSize = size;
        this.setState({pager});
    };

    onSearch = (param = []) => {
        // set downloadPermissions
        this.setState({
            downloadPermissions: param
        });
        this.reportSearch(param);
    };

    // 获取报表详情 同时更新permissions
    reportDetail = callback => {
        // 路由最后一位是id
        const {match: {params: {id}}} = this.props;
        // detail api
        getReportInfo({id}).then(res => {
            const {
                data: {
                    name, description, resportMeasure, reportDimension, mapType,
                    issearch, issummary
                }
            } = res;
            let permissions = [];
            // 筛选条件处理
            if (reportDimension) {
                permissions = reportDimension.filter(item => !item.hidden).map(item => {
                    const i = {
                        dimensionId: item.dimensionId,
                        isinput: item.isinput,
                        dimensionName: item.dimensionName,
                        taskId: item.taskId,
                    };
                    // 设置默认的时间段
                    if (isTimeRange(item.isinput)) {
                        i.filterItems = getRange(item.filterItem);
                        this.setState({
                            period: item.isinput
                        });
                    }
                    else if (item.filterItem instanceof Array) {
                        i.filterItems = item.filterItem;
                    }
                    else if (item.filterItem === '') {
                        i.filterItems = [];
                    }
                    else {
                        i.filterItems = [item.filterItem];
                    }
                    return i;
                });
            }
            this.setState({
                name,
                description,
                reportMeasure: resportMeasure,
                permissions,
                mapType,
                tipText: buildTip(resportMeasure),
                issummary
            }, () => {
                // 是否默认查询
                if (issearch === 1) {
                    // 准备请求参数
                    const params = produce(permissions, draft => {
                        for (const el of draft) {
                            if (isTimeRange(el.isinput)) {
                                const format = getDateFormat(el.isinput);
                                el.filterItems = [
                                    el.filterItems[0].format(format),
                                    el.filterItems[1].format(format)
                                ];
                            }
                        }
                    });
                        // 请求获取详情
                    this.onSearch(params);
                }

                if (callback) {
                    callback();
                }
            });
        })
            .catch(error => {
                if (error) {
                    console.log(error, 'error');
                }
            });
    };

    // 查询获取数据详情
    reportSearch = permissions => {
        const {period, issummary} = this.state;
        this.setState({isloading: true});

        const {match: {params: {id}}} = this.props;
        // 只请求有 参数维度
        permissions = permissions.filter(item => item.filterItems.length > 0);
        const param = {
            id,
            permissions,
            issummary
        };
        fetchReports(param)
            .then(res => {
                const {columns, dataSource, summarySource} = res.data;
                // 渲染table
                const tableColumns = columns.map((item, index) => {
                    const lastComumn = index === columns.length - 1;
                    const columnItem = {
                        dataIndex: item.key,
                        key: item.key,
                        title: (
                            <Tooltip placement="topLeft" title={item.title}>
                                <span className="tableColumn">
                                    {item.title}
                                </span>
                            </Tooltip>
                        ),
                        className: 'normalColumn'
                    };
                    // 判断较短的列
                    if (item.title.includes('人数') || item.title.includes('率')) {
                        columnItem.className = 'smallColumn';
                    }
                    // 最后一列
                    if (lastComumn) {
                        columnItem.className = 'extendColumn';
                    }

                    columnItem.render = (text, record) => {
                        if (text) {
                            const Index = text.indexOf('</a>');
                            if (Index > -1) {
                                const titleIndex = text.lastIndexOf('>', Index);
                                let title = text.slice(titleIndex + 1, Index);
                                if (item.title === '日期' && period === INPUT_TYPE_ENUM.HOUR) {
                                    title = moment(title, FIELD_TIME_FORMAT).format('MM-DD HH:mm');
                                    text = text.slice(0, titleIndex + 1) + title + text.slice(Index);
                                }
                                return (
                                    <Tooltip placement="topLeft" title={title}>
                                        <div className="moreText-table" dangerouslySetInnerHTML={{__html: text}} />
                                    </Tooltip>
                                );
                            }
                            // 长度判断针对 “总计” 的情况
                            if (item.title === '日期' && period === INPUT_TYPE_ENUM.HOUR && text.length > 2) {
                                text = moment(text, FIELD_TIME_FORMAT).format('MM-DD HH:mm');
                            }
                        }
                        return (
                            <Tooltip placement="topLeft" title={text}>
                                <div className="moreText-table">
                                    {text}
                                </div>
                            </Tooltip>
                        );
                    };
                    if (item.key.indexOf('field') > -1 || item.title === '日期') {
                        if (item.title === '日期') {
                            columnItem.sorter = (a, b) => {
                                if (a[item.key] && b[item.key]) {
                                    const IndexA = a[item.key].indexOf('</a>');
                                    const IndexB = b[item.key].indexOf('</a>');
                                    if (IndexA > -1 && IndexB > -1) {
                                        const aSlice = a[item.key].slice(a[item.key]
                                            .lastIndexOf('>', IndexA) + 1, IndexA);
                                        const bSlice = b[item.key].slice(b[item.key]
                                            .lastIndexOf('>', IndexB) + 1, IndexB);
                                        return parseFloat(aSlice) - parseFloat(bSlice);
                                    }
                                }
                                return parseFloat(a[item.key]) - parseFloat(b[item.key]);
                            };
                        }
                        else {
                            columnItem.sorter = (a, b) => parseFloat(a[item.key]) - parseFloat(b[item.key]);
                        }
                        item.sortDirections = ['descend', 'ascend'];
                    }
                    return columnItem;
                });

                const columnsFilter = columns.filter(item => item.title === '日期');
                const dateDim = columnsFilter.length ? columnsFilter[0].key : null;

                // 总计列判断
                if (issummary && summarySource.length) {
                    summarySource[0].dimension1 = TOTAL;
                    this.setState({
                        summarySource: [
                            summarySource[0],
                            ...dataSource
                        ]
                    });
                }

                this.setState({
                    isloading: false,
                    dataSource,
                    tableColumns,
                    dateDim
                });
            })
            .catch(() => {
                this.setState({
                    isloading: false,
                });
            });
    };

    // 下载
    handleDownload = () => {
        const {match: {params: {id}}} = this.props;
        let {downloadPermissions, name, issummary} = this.state;
        // 只请求有 参数维度
        downloadPermissions = downloadPermissions.filter(item => item.filterItems.length > 0);
        const param = {
            id,
            permissions: downloadPermissions,
            issummary
        };
        this.setState({
            downLoading: true
        });
        downloadReports(param, name, this.callback).catch(() => {
            message.error('下载失败，请重试！');
            this.setState({
                downLoading: false
            });
        });
    };

    callback = () => {
        this.setState({
            downLoading: false
        });
    };

    render() {
        const {match: {params: {id}}} = this.props;
        const {
            name, description, reportMeasure, tipText, permissions,
            isloading, tableColumns, dataSource, summarySource, pager, mapType, downLoading,
            period, dateDim, issummary
        } = this.state;

        // 报表描述
        const reportHeader = (
            <>
                <span className="desSpan">
                    {name}
                    <Tooltip title={description}>
                        <QuestionCircleOutlined class="desIcon" />
                    </Tooltip>
                </span>
            </>
        );

        return (
            <div className="commonReport">
                <Card title={reportHeader}>
                    <SearchForm
                        id={id}
                        data={permissions}
                        onSearch={this.onSearch}
                        isLoading={isloading}
                    />
                </Card>
                <Card class="divide">
                    {
                        mapType.indexOf('1') > -1 && (
                            <Spin spinning={isloading} tip="数据加载中...">
                                <LineChart
                                    reportMeasure={reportMeasure}
                                    dataSource={dataSource}
                                    period={period}
                                    dateDim={dateDim}
                                />
                            </Spin>
                        )
                    }
                    {
                        mapType.includes(1) && mapType.includes(2) && <hr style={{borderTop: '1px solid #e9e9e9'}} />
                    }
                    {
                        mapType.indexOf('2') > -1 && (
                            <>
                                <div className="detailContent">
                                    <h3 className="title" style={{display: 'inline-block'}}>
                                        数据详情
                                        <Tooltip placement="topLeft" overlayClassName="measure-tooltip" title={tipText}>
                                            <QuestionCircleOutlined class="desIcon" />
                                        </Tooltip>
                                    </h3>
                                    <div className="rightBtn">
                                        <Button
                                            type="primary"
                                            onClick={this.handleDownload}
                                            loading={downLoading}
                                            disabled={!dataSource.length}
                                        >
                                            下载
                                        </Button>
                                    </div>
                                </div>
                                <DataDetail
                                    pagination={pager}
                                    isLoading={isloading}
                                    dataSource={issummary ? summarySource : dataSource}
                                    columns={tableColumns}
                                    onPageChange={this.onPageChange}
                                    scroll={{x: (tableColumns.length * 140 + 20)}}
                                    rowClassName={(record, index) => {
                                        if (record.dimension1 === TOTAL) {
                                            return 'rowTotal';
                                        }
                                    }}
                                />
                            </>
                        )
                    }
                </Card>
            </div>
        );
    }
}

export default withRouter(ReportIndex);
